<template>
  <div class="admin-layout">
    <!-- 侧边菜单栏 -->
    <Sidebar :is-collapse="isCollapse" />

    <!-- 右侧内容区域 -->
    <div class="content-wrapper">
      <!-- 顶部导航栏 -->
      <Navbar
        :is-collapse="isCollapse"
        :toggle-sidebar="toggleSidebar"
        :user-avatar="userAvatar"
      />

      <!-- 标签页 -->
      <div class="tabs-container">
        <el-tabs 
          v-model="activeTab" 
          type="card" 
          @tab-remove="removeTab"
          @tab-click="handleTabClick"
          class="page-tabs"
        >
          <el-tab-pane
            v-for="tab in tabs"
            :key="tab.name"
            :label="tab.title"
            :name="tab.name"
            :closable="tab.closable"
          />
        </el-tabs>
      </div>

      <!-- 主内容区域 -->
      <div class="main-content">
        <router-view />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import Sidebar from '@/components/common/Sidebar.vue'
import Navbar from '@/components/common/Navbar.vue'
import { useMenuStore } from '../stores/menu'

const router = useRouter()
const route = useRoute()

const menuStore = useMenuStore()

// 响应式数据
const isCollapse = ref(false) // 控制侧边栏的展开和折叠
const userAvatar = ref('') // 用户头像地址
const activeTab = ref('dashboard') // 当前激活的标签页
const tabs = ref([
  { name: 'dashboard', title: '工作台', closable: false } // 默认标签页
])

// 路由名称映射
const routeNames = {
  '/dashboard': '工作台',
  '/users/list': '用户列表',
  '/users/profile': '个人设置',
  '/permissions/roles': '角色管理',
  '/permissions/menus': '菜单管理',
  '/permissions/items': '权限项管理',
  '/content/articles': '文章管理',
  '/content/files': '文件管理',
  '/system/settings': '系统设置',
  '/system/logs': '日志管理'
}

// 方法
const toggleSidebar = () => {
  isCollapse.value = !isCollapse.value
}

const addTab = (path) => {
  const tabName = path === '/dashboard' ? 'dashboard' : path.replace(/\//g, '_')
  if (tabName === 'dashboard') {
    activeTab.value = 'dashboard'
    router.push('/dashboard')
    return
  }

  const title = routeNames[path]
  if (!title) return

  const existingTab = tabs.value.find(tab => tab.name === tabName)
  if (!existingTab) {
    tabs.value.push({
      name: tabName,
      title: title,
      closable: true
    })
  }
  activeTab.value = tabName
}

const removeTab = (tabName) => {
  const index = tabs.value.findIndex(tab => tab.name === tabName)
  if (index > -1) {
    tabs.value.splice(index, 1)
    if (activeTab.value === tabName) {
      const newActiveTab = tabs.value[Math.max(0, index - 1)]
      activeTab.value = newActiveTab.name
      if (newActiveTab.name === 'dashboard') {
        router.push('/dashboard')
        return
      }
      const path = newActiveTab.name.replace(/_/g, '/')
      router.push(path)
    }
  }
}

const handleTabClick = (tab) => {
  const path = tab.props.name.replace(/_/g, '/')
  if (path === 'dashboard') {
    activeTab.value = 'dashboard'
    router.push('/dashboard')
    return
  }
  router.push(path)
}

// 监听路由变化
watch(() => route.path, (newPath) => {
  addTab(newPath)
}, { immediate: true })

// 全局监听菜单变化
watch(
  () => menuStore.lastUpdated,
  () => {
    console.log('检测到菜单变化，刷新应用状态')
  }
)
</script>

<style scoped>
.admin-layout {
  height: 100vh;
  width: 100vw;
  display: flex;
  flex-direction: row;
  overflow: hidden;
}

.sidebar {
  background-color: #304156;
  transition: width 0.28s;
  overflow: hidden;
  height: 100vh;
  flex-shrink: 0;
  width: 250px;
}

.sidebar.collapsed {
  width: 64px;
}

.content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  height: 100vh;
  overflow: hidden;
  min-width: 0;
  width: 100%;
}

.tabs-container {
  background-color: #fff;
  border-bottom: 1px solid #e4e7ed;
  padding: 0 20px;
  height: 40px;
  flex-shrink: 0;
  width: 100%;
}

.page-tabs {
  margin-top: 0;
  width: 100%;
}

.page-tabs :deep(.el-tabs__header) {
  margin-bottom: 0;
  width: 100%;
}

.page-tabs :deep(.el-tabs__nav) {
  border: none;
  width: 100%;
}

.page-tabs :deep(.el-tabs__item) {
  border: 1px solid #e4e7ed;
  border-bottom: none;
  margin-right: 4px;
  border-radius: 4px 4px 0 0;
}

.page-tabs :deep(.el-tabs__item.is-active) {
  background-color: #f0f9ff;
  color: #409eff;
  border-color: #409eff;
}

.main-content {
  background-color: #f5f5f5;
  padding: 20px;
  overflow-y: auto;
  overflow-x: hidden;
  flex: 1;
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}

/* 全局下拉菜单层级 */
:global(.el-dropdown-menu),
:global(.el-popper) {
  z-index: 9999 !important;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .search-input {
    width: 150px;
  }
}

@media (max-width: 768px) {
  .search-input {
    width: 120px;
  }
  
  .header-right {
    gap: 10px;
  }
  
  .username {
    display: none;
  }
  
  .header {
    padding: 0 15px;
  }
  
  .tabs-container {
    padding: 0 15px;
  }
  
  .main-content {
    padding: 15px;
  }
}

@media (max-width: 480px) {
  .breadcrumb {
    display: none;
  }
  
  .search-input {
    width: 100px;
  }
  
  .header {
    padding: 0 10px;
  }
  
  .collapse-btn {
    margin-right: 10px;
  }
}
</style>